package hikari.gui;

import com.gooddies.wiring.annotations.Wire;
import com.gooddies.wiring.annotations.WiringComponent;
import hikari.gui.assets.AssetsTree;
import hikari.gui.guicomponents.easydrag.DefaultDrop;
import hikari.gui.guicomponents.easydrag.listeners.DropListener;
import hikari.gui.panels.Main3dPanel;
import hikari.managers.Manager3D;
import hikari.managers.TemplateManager;
import hikari.objects3d.Custom3DObject;
import hikari.utils.Utils;
import java.awt.Component;
import java.awt.dnd.DropTargetDropEvent;
import javax.swing.tree.TreePath;

/**
 * @author sad
 */
@WiringComponent(singleton = true)
public class Main3dPanelDragDrop {

    @Wire
    private AssetsTree assetsTree;
    @Wire
    private Manager3D manager3D;
    @Wire
    private Utils utils;

    private Main3dPanelDragDrop() {
    }

    public void initDragDrop(Main3dPanel panel3d) {

        DefaultDrop drop = new DefaultDrop(panel3d, new DropListener() {
            @Override
            public void performDrop(Component source, Component target, DropTargetDropEvent dtde, Object data) {
                if (data instanceof TreePath && source == assetsTree) {
                    String path = assetsTree.treePathToFilePath((TreePath) data);
                    String extension = utils.getFileExtension(path);
                    if (assetsTree.isExtension3dModel(extension)) {
                        importModel(path, dtde.getLocation().x, dtde.getLocation().y);
                    }
                    if (assetsTree.isExtensionTemplate(extension)) {
                        importTemplate(path, dtde.getLocation().x, dtde.getLocation().y);
                    }
                }
            }

            @Override
            public boolean canDrop(Component source, Component target, Object data, int x, int y) {
                if (data instanceof TreePath && source == assetsTree) {
                    String path = assetsTree.treePathToFilePath((TreePath) data);
                    String extension = utils.getFileExtension(path);
                    if (assetsTree.isExtension3dModel(extension)) {
                        return true;
                    }
                    if (assetsTree.isExtensionTemplate(extension)) {
                        return true;
                    }
                }

                return false;
            }
        });

        drop.setEnabled(true);
    }

    private void importTemplate(String path, int x, int y) {
        TemplateManager.getInstance().loadTemplate(path, x, y);
    }

    private void importModel(String path, int x, int y) {
        Custom3DObject object3d = Custom3DObject.loadModelByPath(path, manager3D.getSceneManager());
        manager3D.AddObject(object3d);
    }
}
